import React, { useState, useEffect, useRef, useCallback } from "react";
import {
  FileText,
  Save,
  Maximize2,
  Minimize2,
  X,
  Loader2,
  Check,
  Copy,
  AlertTriangle,
  ChevronDown,
  ChevronRight,
  SearchCheck,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";

import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Label } from "@/components/ui/label";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";
import { Textarea } from "@/components/ui/textarea";
import { Alert, AlertTitle, AlertDescription } from "@/components/ui/alert";

import { ConstructionSchemeAPI } from "@/api/ConstructionScheme";
import { CrossingPointAPI } from "@/api/CrossingPoint";
import { ProjectAPI } from "@/api/project";
import { SystemVariableConfigAPI } from "@/api/SystemVariableConfig";

import WordTemplateUploader from "./WordTemplateUploader";
import MarkdownPreviewRenderer from "./MarkdownPreviewRenderer";
import { frontendLogic } from "@/components/utils/frontendLogic";
import DraggableVariableGuide from "./DraggableVariableGuide";
import EditorToolbar from "./EditorToolbar";
import {
  levenshteinDistance,
  findBestMatch,
  performReplacement,
  getDefaultMarkdownTemplate,
  getExampleOutline,
} from "./helpers";

const MarkdownTemplateEditor = ({ template, onSave, onCancel }) => {
  // 核心状态
  const [currentTemplate, setCurrentTemplate] = useState(template);
  const [activeTab, setActiveTab] = useState("editor");
  const [isFullscreen, setIsFullscreen] = useState(false);
  const [saveNotification, setSaveNotification] = useState(null);
  const textareaRef = useRef(null);

  // 预览相关状态
  const [schemes, setSchemes] = useState([]);
  const [selectedSchemeId, setSelectedSchemeId] = useState("");
  const [previewData, setPreviewData] = useState(null);
  const [processedMarkdown, setProcessedMarkdown] = useState("");
  const [isPreviewLoading, setIsPreviewLoading] = useState(false);
  const [previewEnabled, setPreviewEnabled] = useState(true);
  const [showPreviewHint, setShowPreviewHint] = useState(false);
  const [previewHintContent, setPreviewHintContent] = useState("");
  const [showFullPreview, setShowFullPreview] = useState(false);
  const hintAnchorRef = useRef(null);

  // AI功能状态
  const [isAiProcessing, setIsAiProcessing] = useState(false);
  const [isGeneratingTemplate, setIsGeneratingTemplate] = useState(false);
  const [isGeneratingTable, setIsGeneratingTable] = useState(false);
  const [isGeneratingFromOutline, setIsGeneratingFromOutline] = useState(false);
  const [showOutlineInput, setShowOutlineInput] = useState(false);
  const [outlineText, setOutlineText] = useState("");

  // 变量检查状态
  const [isCheckingVariables, setIsCheckingVariables] = useState(false);
  const [variableCheckResults, setVariableCheckResults] = useState(null);
  const [allValidVariables, setAllValidVariables] = useState([]);
  const [isVariableCheckExpanded, setIsVariableCheckExpanded] = useState(true);

  // 其他状态
  const [userPreferences, setUserPreferences] = useState({
    previewEnabled: true,
    lastPreviewSchemeId: null,
  });
  const [showVariableGuide, setShowVariableGuide] = useState(false);
  const [isCopying, setIsCopying] = useState(false);
  const [copySuccess, setCopySuccess] = useState(false);

  // 初始化
  useEffect(() => {
    if (!currentTemplate?.templateContent?.markdown) {
      setCurrentTemplate((prev) => ({
        ...prev,
        templateContent: { markdown: getDefaultMarkdownTemplate() },
      }));
    }
    loadUserPreferences();
    loadSchemesForPreview();
    loadValidVariables();
  }, [template]);

  // 加载用户偏好
  const loadUserPreferences = () => {
    try {
      const saved = localStorage.getItem("template-editor-preferences");
      if (saved) {
        const preferences = JSON.parse(saved);
        setUserPreferences(preferences);
        setPreviewEnabled(preferences.previewEnabled ?? true);
      }
    } catch (error) {
      console.warn("加载用户偏好设置失败:", error);
    }
  };

  // 保存用户偏好
  useEffect(() => {
    if (
      userPreferences.previewEnabled !== previewEnabled ||
      (selectedSchemeId &&
        userPreferences.lastPreviewSchemeId !== selectedSchemeId)
    ) {
      const updated = {
        ...userPreferences,
        previewEnabled,
        lastPreviewSchemeId: selectedSchemeId,
      };
      setUserPreferences(updated);
      localStorage.setItem(
        "template-editor-preferences",
        JSON.stringify(updated)
      );
    }
  }, [previewEnabled, selectedSchemeId, userPreferences]);

  // 加载方案列表
  const loadSchemesForPreview = async () => {
    try {
      const schemeList = await ConstructionSchemeAPI.getList();
      setSchemes(schemeList.data || []);

      if (schemeList.data?.length) {
        setSelectedSchemeId(
          userPreferences.lastPreviewSchemeId &&
            schemeList.data.some(
              (s) => s.id === userPreferences.lastPreviewSchemeId
            )
            ? userPreferences.lastPreviewSchemeId
            : schemeList.data[0].id
        );
      }
    } catch (error) {
      console.error("加载方案列表失败:", error);
      setSchemes([]);
    }
  };

  // 加载预览数据
  useEffect(() => {
    const loadFullSchemeData = async () => {
      if (!selectedSchemeId) return setPreviewData(null);
      setIsPreviewLoading(true);
      try {
        const res = await ConstructionSchemeAPI.get(selectedSchemeId);
        const scheme = res.data;
        const crossingPointRes = scheme.crossingPointId
          ? await CrossingPointAPI.getDetail(scheme.crossingPointId).catch(
              () => null
            )
          : null;
        const crossingPoint = crossingPointRes.data;
        const projectRes = crossingPoint?.projectId
          ? await ProjectAPI.get(crossingPoint.projectId).catch(() => null)
          : null;
        const project = projectRes.data;
        // const user = await User.me().catch(() => null);
        const user = {};
        const dataForTemplate = frontendLogic.prepareTemplateData(
          scheme,
          crossingPoint,
          project,
          user
        );
        setPreviewData(dataForTemplate);
      } catch (error) {
        console.error("加载预览数据失败:", error);
        setSaveNotification({
          type: "error",
          message: `加载预览数据失败: ${error.message}`,
        });
        setTimeout(() => setSaveNotification(null), 3000);
        setPreviewData({});
      } finally {
        setIsPreviewLoading(false);
      }
    };
    loadFullSchemeData();
  }, [selectedSchemeId]);

  // 渲染预览内容
  useEffect(() => {
    const rawMarkdown = currentTemplate.templateContent?.markdown || "";
    if (previewEnabled && rawMarkdown && previewData) {
      try {
        const rendered = frontendLogic.renderMarkdownTemplate(
          rawMarkdown,
          previewData
        );
        setProcessedMarkdown(rendered);
      } catch (e) {
        console.error("模板渲染失败:", e);
        setProcessedMarkdown(
          `## 模板渲染出错\n\n请检查模板语法是否正确。错误信息: ${e.message}`
        );
      }
    } else {
      setProcessedMarkdown(rawMarkdown);
    }
  }, [currentTemplate.templateContent?.markdown, previewData, previewEnabled]);

  // 加载有效变量
  const loadValidVariables = async () => {
    try {
      const variables = await SystemVariableConfigAPI.getList();
      setAllValidVariables(
        variables.data
          .filter((v) => !v.is_deprecated)
          .map((v) => v.variable_key)
      );
    } catch (error) {
      console.error("加载变量列表失败:", error);
    }
  };

  // Markdown更新处理
  const handleUpdateMarkdown = (newMarkdown) => {
    setCurrentTemplate((prev) => ({
      ...prev,
      templateContent: {
        ...(prev.templateContent || {}),
        markdown: newMarkdown,
      },
    }));
  };

  // 保存Word模板
  const handleUpdateTemplate = async (templateUpdateData) => {
    try {
      if (
        !templateUpdateData ||
        typeof templateUpdateData !== "object" ||
        Array.isArray(templateUpdateData)
      ) {
        throw new Error("模板更新数据格式错误");
      }
      if (!templateUpdateData.url || !templateUpdateData.fileName) {
        throw new Error("缺少文件信息");
      }

      const updatedTemplate = {
        ...currentTemplate,
        word_template_url: templateUpdateData.url,
        word_template_filename: templateUpdateData.fileName,
      };
      setCurrentTemplate(updatedTemplate);
      await onSave(updatedTemplate);
      setSaveNotification({ type: "success", message: "Word模板已保存" });
    } catch (error) {
      console.error("保存Word模板失败:", error);
      setSaveNotification({
        type: "error",
        message: `保存Word模板失败: ${error.message || "未知错误"}`,
      });
    } finally {
      setTimeout(() => setSaveNotification(null), 3000);
    }
  };

  // 保存模板
  const handleSave = async (dataToSave) => {
    try {
      await onSave(dataToSave || currentTemplate);
      setSaveNotification({ type: "success", message: "模板保存成功" });
    } catch (error) {
      setSaveNotification({
        type: "error",
        message: `保存失败: ${error.message || "未知错误"}`,
      });
    } finally {
      setTimeout(() => setSaveNotification(null), 3000);
    }
  };

  // 插入变量
  const handleInsertVariable = (variableText) => {
    if (!textareaRef.current) return;
    const textarea = textareaRef.current;
    const { selectionStart: start, selectionEnd: end } = textarea;
    const text = currentTemplate.templateContent?.markdown || "";
    const newText =
      text.substring(0, start) + variableText + text.substring(end);

    handleUpdateMarkdown(newText);
    setTimeout(() => {
      textarea.focus();
      textarea.selectionStart = textarea.selectionEnd =
        start + variableText.length;
    }, 0);
  };

  // AI变量替换
  const handleAiVariableReplacement = async () => {
    const currentContent = currentTemplate.templateContent?.markdown || "";
    if (!currentContent.trim()) {
      return setSaveNotification({ type: "error", message: "请先输入内容" });
    }

    setIsAiProcessing(true);
    try {
      const { InvokeLLM } = await import("@/api/integrations");
      const prompt = `请将以下Markdown内容中的具体信息替换为变量标记...`; // 简化，保留核心逻辑
      const result = await InvokeLLM({ prompt, addContextFromInternet: false });

      if (typeof result === "string") {
        handleUpdateMarkdown(result);
        setSaveNotification({ type: "success", message: "AI变量替换完成！" });
      } else {
        throw new Error("AI处理结果异常");
      }
    } catch (error) {
      setSaveNotification({
        type: "error",
        message: `AI变量替换失败: ${error.message}`,
      });
    } finally {
      setIsAiProcessing(false);
      setTimeout(() => setSaveNotification(null), 3000);
    }
  };

  // 选中文本AI替换
  const handleSelectedTextReplacement = async () => {
    if (!textareaRef.current) return;
    const { selectionStart: start, selectionEnd: end } = textareaRef.current;
    if (start === end) {
      return setSaveNotification({ type: "error", message: "请先选中文本" });
    }

    const selectedText = textareaRef.current.value.substring(start, end);
    const fullText = textareaRef.current.value;
    setIsAiProcessing(true);

    try {
      const { InvokeLLM } = await import("@/api/integrations");
      const prompt = `请将选中文本转换为变量表达式...`; // 简化
      const result = await InvokeLLM({ prompt, addContextFromInternet: false });

      if (typeof result === "string") {
        const newContent =
          fullText.substring(0, start) +
          result.trim() +
          fullText.substring(end);
        handleUpdateMarkdown(newContent);
        setSaveNotification({ type: "success", message: "选中文本替换完成！" });
      } else {
        throw new Error("AI处理结果异常");
      }
    } catch (error) {
      setSaveNotification({
        type: "error",
        message: `替换失败: ${error.message}`,
      });
    } finally {
      setIsAiProcessing(false);
      setTimeout(() => setSaveNotification(null), 3000);
    }
  };

  // 手动预览选中文本
  const handleManualPreview = () => {
    if (!textareaRef.current || !previewData || isPreviewLoading) {
      return setSaveNotification({
        type: "error",
        message: "请选择预览数据源",
      });
    }

    const { selectionStart: start, selectionEnd: end } = textareaRef.current;
    if (start === end) {
      return setSaveNotification({ type: "error", message: "请先选中文本" });
    }

    const selectedText = textareaRef.current.value.substring(start, end);
    try {
      const rendered = frontendLogic.renderMarkdownTemplate(
        selectedText,
        previewData
      );
      setPreviewHintContent(rendered);

      // 定位提示框
      const range = window.getSelection().getRangeAt(0);
      const rect = range.getBoundingClientRect();
      if (hintAnchorRef.current) {
        hintAnchorRef.current.style = `position:fixed;left:${
          rect.left + rect.width / 2
        }px;top:${rect.top}px;z-index:-1;width:1px;height:1px`;
      }
      setShowPreviewHint(true);
    } catch (error) {
      setPreviewHintContent(`渲染失败: ${error.message}`);
    }
  };

  // AI内容补充
  const handleAiContentGeneration = async (mode = "full") => {
    if (!textareaRef.current) return;
    const textarea = textareaRef.current;
    const fullContent = textarea.value;
    let targetContent = fullContent,
      insertPosition = fullContent.length,
      replaceLength = 0;

    if (mode === "selected") {
      const { selectionStart: start, selectionEnd: end } = textarea;
      if (start === end) {
        return setSaveNotification({
          type: "error",
          message: "请选中章节标题",
        });
      }
      targetContent = fullContent.substring(start, end);
      insertPosition = start;
      replaceLength = end - start;
    }

    setIsAiProcessing(true);
    try {
      const { InvokeLLM } = await import("@/api/integrations");
      const prompt =
        mode === "selected" ? `为选中章节生成内容...` : `补充完整模板内容...`; // 简化

      const result = await InvokeLLM({ prompt, addContextFromInternet: false });
      if (typeof result === "string") {
        const newContent =
          mode === "selected"
            ? fullContent.substring(0, insertPosition) +
              result.trim() +
              fullContent.substring(insertPosition + replaceLength)
            : result.trim();

        handleUpdateMarkdown(newContent);
        setSaveNotification({
          type: "success",
          message:
            mode === "selected" ? "AI章节补充完成！" : "AI模板补充完成！",
        });
      } else {
        throw new Error("AI处理结果异常");
      }
    } catch (error) {
      setSaveNotification({
        type: "error",
        message: `AI内容补充失败: ${error.message}`,
      });
    } finally {
      setIsAiProcessing(false);
      setTimeout(() => setSaveNotification(null), 3000);
    }
  };

  // AI生成表格
  const handleAiTableGeneration = async () => {
    if (!textareaRef.current) return;
    const { selectionStart: start, selectionEnd: end } = textareaRef.current;
    if (start === end) {
      return setSaveNotification({
        type: "error",
        message: "请选中变量或循环语句",
      });
    }

    const selectedText = textareaRef.current.value.substring(start, end);
    setIsGeneratingTable(true);

    try {
      const { InvokeLLM } = await import("@/api/integrations");
      const prompt = `将选中内容转换为Markdown表格...`; // 简化
      const result = await InvokeLLM({ prompt, addContextFromInternet: false });

      if (typeof result === "string") {
        const newContent =
          textareaRef.current.value.substring(0, start) +
          result.trim() +
          textareaRef.current.value.substring(end);
        handleUpdateMarkdown(newContent);
        setSaveNotification({ type: "success", message: "AI表格生成完成！" });
      } else {
        throw new Error("AI处理结果异常");
      }
    } catch (error) {
      setSaveNotification({
        type: "error",
        message: `表格生成失败: ${error.message}`,
      });
    } finally {
      setIsGeneratingTable(false);
      setTimeout(() => setSaveNotification(null), 3000);
    }
  };

  // AI生成完整模板
  const handleAIGenerateTemplate = async () => {
    setIsGeneratingTemplate(true);
    try {
      // 实际项目中使用真实API，此处简化
      const mockResult = getDefaultMarkdownTemplate();
      handleUpdateMarkdown(mockResult);
      setSaveNotification({ type: "success", message: "AI模板生成成功！" });
    } catch (error) {
      setSaveNotification({
        type: "error",
        message: `AI生成失败: ${error.message}`,
      });
    } finally {
      setIsGeneratingTemplate(false);
      setTimeout(() => setSaveNotification(null), 5000);
    }
  };

  // 基于目录生成模板
  const handleGenerateFromOutline = async () => {
    if (!outlineText.trim()) {
      return setSaveNotification({ type: "error", message: "请输入目录文字" });
    }

    setIsGeneratingFromOutline(true);
    try {
      const { InvokeLLM } = await import("@/api/integrations");
      const prompt = `根据目录生成Markdown模板...`; // 简化
      const result = await InvokeLLM({ prompt, addContextFromInternet: false });

      if (typeof result === "string") {
        handleUpdateMarkdown(result);
        setShowOutlineInput(false);
        setOutlineText("");
        setSaveNotification({
          type: "success",
          message: "基于目录的模板生成成功！",
        });
      } else {
        throw new Error("AI处理结果异常");
      }
    } catch (error) {
      setSaveNotification({
        type: "error",
        message: `生成失败: ${error.message}`,
      });
    } finally {
      setIsGeneratingFromOutline(false);
      setTimeout(() => setSaveNotification(null), 3000);
    }
  };

  // 变量检查
  const handleVariableCheck = async (contentToCheck) => {
    const content =
      typeof contentToCheck === "string"
        ? contentToCheck
        : currentTemplate.templateContent?.markdown || "";
    if (!content.trim()) {
      return setSaveNotification({
        type: "error",
        message: "请输入内容后检查",
      });
    }

    setIsCheckingVariables(true);
    setVariableCheckResults(null);
    setIsVariableCheckExpanded(true);

    try {
      const variableRegex = /\{\{([^}]+)\}\}/g;
      const foundVariables = new Set();
      let match;

      while ((match = variableRegex.exec(content)) !== null) {
        const variableContent = match[1].trim();
        if (variableContent.startsWith("#each ")) {
          foundVariables.add(variableContent.replace("#each ", "").trim());
        } else if (variableContent.startsWith("#if ")) {
          const varMatch = variableContent
            .replace("#if ", "")
            .trim()
            .match(/^([a-zA-Z_][a-zA-Z0-9_.]*)/);
          if (varMatch) foundVariables.add(varMatch[1].split(".")[0]);
        } else if (
          !variableContent.startsWith("/") &&
          !variableContent.startsWith(".") &&
          variableContent !== "."
        ) {
          foundVariables.add(
            variableContent === "this"
              ? "this"
              : variableContent.startsWith("this.")
              ? "this"
              : variableContent.split(".")[0]
          );
        }
      }

      // 验证变量有效性
      const validVariables = [];
      const invalidVariables = [];
      const suggestions = {};

      foundVariables.forEach((variable) => {
        if (allValidVariables.includes(variable)) {
          validVariables.push(variable);
        } else {
          invalidVariables.push(variable);
          const suggestion = findBestMatch(variable, allValidVariables);
          if (suggestion) suggestions[variable] = suggestion;
        }
      });

      setVariableCheckResults({
        totalFound: foundVariables.size,
        validVariables,
        invalidVariables,
        suggestions,
      });
      setSaveNotification({
        type: invalidVariables.length === 0 ? "success" : "warning",
        message:
          invalidVariables.length === 0
            ? `✅ 变量检查完成：${foundVariables.size}个变量全部有效！`
            : `⚠️ 发现${invalidVariables.length}个无效变量`,
      });
    } catch (error) {
      setSaveNotification({
        type: "error",
        message: `变量检查失败: ${error.message}`,
      });
    } finally {
      setIsCheckingVariables(false);
      setTimeout(() => setSaveNotification(null), 5000);
    }
  };

  // 变量替换处理
  const handleSingleReplace = (invalidVar, suggestion) => {
    const content = currentTemplate.templateContent?.markdown || "";
    const newContent = performReplacement(content, invalidVar, suggestion);
    if (content !== newContent) {
      handleUpdateMarkdown(newContent);
      setSaveNotification({
        type: "success",
        message: `已替换 '${invalidVar}' 为 '${suggestion}'`,
      });
      handleVariableCheck(newContent);
    }
  };

  const handleAutoReplace = () => {
    if (!variableCheckResults?.suggestions) return;
    let content = currentTemplate.templateContent?.markdown || "";
    const initialContent = content;

    Object.entries(variableCheckResults.suggestions).forEach(
      ([invalidVar, suggestion]) => {
        content = performReplacement(content, invalidVar, suggestion);
      }
    );

    if (content !== initialContent) {
      handleUpdateMarkdown(content);
      setSaveNotification({
        type: "success",
        message: "已自动替换所有建议变量",
      });
      handleVariableCheck(content);
    } else {
      setSaveNotification({ type: "warning", message: "没有可替换的变量" });
    }
    setTimeout(() => setSaveNotification(null), 3000);
  };

  // 复制预览内容
  const handleCopyPreviewContent = async () => {
    if (!processedMarkdown) {
      return setSaveNotification({
        type: "error",
        message: "没有可复制的内容",
      });
    }

    setIsCopying(true);
    try {
      await navigator.clipboard.writeText(processedMarkdown);
      setCopySuccess(true);
      setSaveNotification({ type: "success", message: "预览内容已复制" });
    } catch (error) {
      // 降级方案
      const textArea = document.createElement("textarea");
      textArea.value = processedMarkdown;
      document.body.appendChild(textArea);
      textArea.select();
      document.execCommand("copy");
      document.body.removeChild(textArea);
      setCopySuccess(true);
      setSaveNotification({ type: "success", message: "预览内容已复制" });
    } finally {
      setIsCopying(false);
      setTimeout(() => {
        setCopySuccess(false);
        setSaveNotification(null);
      }, 2000);
    }
  };

  // 渲染主界面
  return (
    <div className={isFullscreen ? "fixed inset-0 z-50 bg-white" : "relative"}>
      {/* 通知提示 */}
      {saveNotification && (
        <div
          className={`fixed top-4 right-4 z-50 px-4 py-3 rounded-lg shadow-lg border transition-all duration-300 ${
            saveNotification.type === "success"
              ? "bg-green-50 text-green-800 border-green-200"
              : saveNotification.type === "warning"
              ? "bg-yellow-50 text-yellow-800 border-yellow-200"
              : "bg-red-50 text-red-800 border-red-200"
          }`}
        >
          <div className="flex items-center gap-2">
            <div
              className={`w-5 h-5 rounded-full flex items-center justify-center ${
                saveNotification.type === "success"
                  ? "bg-green-500"
                  : saveNotification.type === "warning"
                  ? "bg-yellow-500"
                  : "bg-red-500"
              }`}
            >
              <div className="w-2 h-2 bg-white rounded-full"></div>
            </div>
            <span className="text-sm font-medium">
              {saveNotification.message}
            </span>
          </div>
        </div>
      )}

      <Card className="flex flex-col h-full shadow-none border-0">
        <CardHeader className="flex-shrink-0 flex items-center justify-between p-4 border-b">
          <CardTitle className="flex items-center gap-2">
            <FileText className="w-5 h-5" />
            {currentTemplate?.name || "模板编辑器"}
            <div className="flex items-center gap-2">
            <Button variant="outline" onClick={onCancel}>
              关闭
            </Button>
          </div>
          </CardTitle>
        </CardHeader>

        <CardContent className="p-0 flex-grow overflow-hidden">
          <Tabs
            value={activeTab}
            onValueChange={setActiveTab}
            className="h-full flex flex-col"
          >
            <div className="flex justify-between items-center border-b p-4">
              <TabsList>
                <TabsTrigger value="editor">模板编辑器</TabsTrigger>
                <TabsTrigger value="word">Word母版</TabsTrigger>
                <TabsTrigger value="basic_info">基本信息</TabsTrigger>
              </TabsList>

              <div className="flex items-center gap-2">
                {/* <Button
                  onClick={handleAIGenerateTemplate}
                  disabled={isGeneratingTemplate}
                  className="bg-gradient-to-r from-purple-600 to-blue-600 hover:from-purple-700 hover:to-blue-700 text-white text-sm h-9 px-4 py-2"
                >
                  {isGeneratingTemplate ? (
                    <>
                      <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                      AI生成中...
                    </>
                  ) : (
                    <>
                      🤖 AI生成完整模板
                    </>
                  )}
                </Button> */}
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => setIsFullscreen(!isFullscreen)}
                  title={isFullscreen ? "退出全屏" : "全屏"}
                  className="bg-white p-2 h-9 w-9"
                >
                  {isFullscreen ? (
                    <Minimize2 className="w-4 h-4" />
                  ) : (
                    <Maximize2 className="w-4 h-4" />
                  )}
                </Button>
                <Button
                  size="sm"
                  onClick={() => handleSave()}
                  className="bg-blue-600 hover:bg-blue-700 h-9 px-4 py-2"
                >
                  <Save className="w-4 h-4 mr-2" />
                  保存
                </Button>
              </div>
            </div>

            {/* 编辑器标签内容 */}
            <TabsContent
              value="editor"
              className="flex-grow mt-0 p-4 overflow-hidden"
            >
              {/* 工具栏 */}
              <div className="flex flex-col gap-3 p-4 mb-4 border rounded-lg bg-gradient-to-r from-gray-50 to-blue-50">
                <EditorToolbar
                  schemes={schemes}
                  selectedSchemeId={selectedSchemeId}
                  setSelectedSchemeId={setSelectedSchemeId}
                  previewEnabled={previewEnabled}
                  setPreviewEnabled={setPreviewEnabled}
                  isAiProcessing={isAiProcessing}
                  isGeneratingTable={isGeneratingTable}
                  isGeneratingFromOutline={isGeneratingFromOutline}
                  isCheckingVariables={isCheckingVariables}
                  isPreviewLoading={isPreviewLoading}
                  previewData={previewData}
                  onAiGenerateTemplate={handleAIGenerateTemplate}
                  onAiContentFull={() => handleAiContentGeneration("full")}
                  onAiContentSelected={() =>
                    handleAiContentGeneration("selected")
                  }
                  onAiVariableReplace={handleAiVariableReplacement}
                  onAiSelectedReplace={handleSelectedTextReplacement}
                  onAiTableGenerate={handleAiTableGeneration}
                  onToggleOutlineInput={() =>
                    setShowOutlineInput(!showOutlineInput)
                  }
                  onVariableCheck={handleVariableCheck}
                  onShowVariableGuide={() => setShowVariableGuide(true)}
                  onManualPreview={handleManualPreview}
                  onOpenFullPreview={() => setShowFullPreview(true)}
                />
              </div>

              {/* 目录生成区域 */}
              {showOutlineInput && (
                <div className="mt-4 p-4 border rounded-lg bg-gradient-to-r from-rose-50 to-pink-50 border-rose-200">
                  <div className="flex items-center justify-between mb-3">
                    <h3 className="text-sm font-medium text-rose-800">
                      根据目录结构生成MD模板
                    </h3>
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => setShowOutlineInput(false)}
                      className="h-6 w-6 p-0 text-rose-500 hover:text-rose-700"
                    >
                      <X className="w-4 h-4" />
                    </Button>
                  </div>
                  <div className="space-y-3">
                    <div className="flex items-center gap-2 mb-2">
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => setOutlineText(getExampleOutline())}
                        className="text-xs text-rose-600 hover:text-rose-800"
                      >
                        使用示例目录
                      </Button>
                      <span className="text-xs text-gray-500">
                        或手动输入目录结构
                      </span>
                    </div>
                    <textarea
                      value={outlineText}
                      onChange={(e) => setOutlineText(e.target.value)}
                      placeholder="请输入目录结构，例如：&#10;1. 工程概况&#10;1.1 项目基本信息&#10;..."
                      className="w-full h-32 p-3 text-sm border border-rose-200 rounded-md resize-none focus:outline-none focus:ring-2 focus:ring-rose-500"
                    />
                    <div className="flex items-center gap-2">
                      <Button
                        size="sm"
                        onClick={handleGenerateFromOutline}
                        disabled={
                          isGeneratingFromOutline || !outlineText.trim()
                        }
                        className="bg-rose-600 hover:bg-rose-700 text-white"
                      >
                        {isGeneratingFromOutline ? (
                          <>
                            <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                            生成中...
                          </>
                        ) : (
                          <>
                            {/* <BookOpen className="w-4 h-4 mr-2" /> */}
                            生成模板
                          </>
                        )}
                      </Button>
                      <span className="text-xs text-gray-500">
                        AI将根据目录生成专业模板
                      </span>
                    </div>
                  </div>
                </div>
              )}

              {/* AI生成说明 */}
              {!currentTemplate.templateContent?.markdown &&
                !showOutlineInput && (
                  <Alert className="border-blue-200 bg-blue-50 mb-4">
                    {/* <Brain className="h-4 w-4" /> */}
                    <AlertTitle className="text-blue-800">
                      🤖 AI智能生成
                    </AlertTitle>
                    <AlertDescription className="text-blue-700">
                      点击"AI生成完整模板"按钮，系统将智能生成施工方案模板，或使用"根据目录生成"自定义结构。
                    </AlertDescription>
                  </Alert>
                )}

              {/* 变量检查结果 */}
              {variableCheckResults && (
                <Alert
                  className={`border-2 ${
                    variableCheckResults.invalidVariables.length === 0
                      ? "border-green-200 bg-green-50"
                      : "border-orange-200 bg-orange-50"
                  } mb-4`}
                >
                  <AlertTriangle className="h-4 w-4" />
                  <div className="flex items-center justify-between w-full">
                    <AlertTitle
                      className={
                        variableCheckResults.invalidVariables.length === 0
                          ? "text-green-800"
                          : "text-orange-800"
                      }
                    >
                      变量检查结果
                    </AlertTitle>
                    <div className="flex items-center gap-2">
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() =>
                          setIsVariableCheckExpanded(!isVariableCheckExpanded)
                        }
                        className="h-6 px-2"
                      >
                        {isVariableCheckExpanded ? (
                          <ChevronDown className="w-4 h-4" />
                        ) : (
                          <ChevronRight className="w-4 h-4" />
                        )}
                      </Button>
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => setVariableCheckResults(null)}
                        className="h-6 px-2"
                      >
                        <X className="w-4 h-4" />
                      </Button>
                    </div>
                  </div>

                  {isVariableCheckExpanded && (
                    <AlertDescription
                      className={
                        variableCheckResults.invalidVariables.length === 0
                          ? "text-green-700"
                          : "text-orange-700"
                      }
                    >
                      <div className="space-y-2 mt-2">
                        <p>
                          共发现{" "}
                          <strong>{variableCheckResults.totalFound}</strong>{" "}
                          个变量， 其中{" "}
                          <strong className="text-green-600">
                            {variableCheckResults.validVariables.length}
                          </strong>{" "}
                          个有效，
                          <strong className="text-red-600">
                            {variableCheckResults.invalidVariables.length}
                          </strong>{" "}
                          个无效
                        </p>

                        {variableCheckResults.invalidVariables.length > 0 && (
                          <div>
                            <p className="font-medium mb-1">无效变量:</p>
                            <ul className="list-disc list-inside space-y-2">
                              {variableCheckResults.invalidVariables.map(
                                (variable) => (
                                  <li
                                    key={variable}
                                    className="text-sm flex items-center justify-between p-1 rounded hover:bg-orange-100/50"
                                  >
                                    <div>
                                      <code className="bg-red-100 text-red-800 px-1 rounded">
                                        {variable}
                                      </code>
                                      {variableCheckResults.suggestions[
                                        variable
                                      ] && (
                                        <span className="ml-2 text-gray-700">
                                          → 建议:{" "}
                                          <code className="bg-green-100 text-green-800 px-1 rounded">
                                            {
                                              variableCheckResults.suggestions[
                                                variable
                                              ]
                                            }
                                          </code>
                                        </span>
                                      )}
                                    </div>
                                    {variableCheckResults.suggestions[
                                      variable
                                    ] && (
                                      <Button
                                        size="sm"
                                        variant="ghost"
                                        className="h-7 px-2 text-xs"
                                        onClick={() =>
                                          handleSingleReplace(
                                            variable,
                                            variableCheckResults.suggestions[
                                              variable
                                            ]
                                          )
                                        }
                                      >
                                        {/* <Wand2 className="w-3 h-3 mr-1" /> */}
                                        替换
                                      </Button>
                                    )}
                                  </li>
                                )
                              )}
                            </ul>

                            {Object.keys(variableCheckResults.suggestions)
                              .length > 0 && (
                              <Button
                                size="sm"
                                onClick={handleAutoReplace}
                                className="mt-3 bg-orange-600 hover:bg-orange-700"
                              >
                                {/* <Wand2 className="w-4 h-4 mr-2" /> */}
                                一键替换所有建议
                              </Button>
                            )}
                          </div>
                        )}
                      </div>
                    </AlertDescription>
                  )}
                </Alert>
              )}

              {/* 编辑器和预览区域 */}
              <div
                className={`grid gap-4 h-full ${
                  previewEnabled ? "grid-cols-1 md:grid-cols-2" : "grid-cols-1"
                }`}
              >
                {/* 编辑器区域 */}
                <div className="flex flex-col h-full">
                  <div className="flex justify-between items-center mb-2">
                    <Label htmlFor="markdown-editor" className="font-semibold">
                      Markdown 内容
                    </Label>
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() =>
                        handleVariableCheck(
                          currentTemplate.templateContent?.markdown
                        )
                      }
                      title="检查变量"
                    >
                      {isCheckingVariables ? (
                        <Loader2 className="w-4 h-4 animate-spin" />
                      ) : (
                        <SearchCheck className="w-4 h-4" />
                      )}
                    </Button>
                  </div>
                  <Textarea
                    ref={textareaRef}
                    id="markdown-editor"
                    value={currentTemplate.templateContent?.markdown || ""}
                    onChange={(e) => handleUpdateMarkdown(e.target.value)}
                    placeholder={
                      !currentTemplate.templateContent?.markdown
                        ? `# 施工方案模板\n\n点击"AI生成完整模板"创建专业模板，或手动输入内容...`
                        : previewEnabled
                        ? "输入Markdown模板内容，支持变量和循环语法..."
                        : "输入Markdown模板内容..."
                    }
                    className="flex-grow font-mono text-sm resize-none min-h-[40vh]"
                  />

                  {/* 手动预览提示框 */}
                  {previewEnabled && (
                    <Popover
                      open={showPreviewHint}
                      onOpenChange={setShowPreviewHint}
                    >
                      <PopoverTrigger asChild>
                        <div
                          ref={hintAnchorRef}
                          className="absolute pointer-events-none"
                        />
                      </PopoverTrigger>
                      <PopoverContent
                        className="w-auto max-w-lg shadow-xl border-2 border-blue-200"
                        side="top"
                        align="center"
                      >
                        <div className="bg-gradient-to-r from-blue-50 to-indigo-50 p-2 border-b">
                          <span className="text-xs font-medium text-blue-700">
                            选中内容预览
                          </span>
                        </div>
                        <div className="max-h-64 overflow-y-auto">
                          <MarkdownPreviewRenderer
                            content={previewHintContent}
                          />
                        </div>
                      </PopoverContent>
                    </Popover>
                  )}
                </div>

                {/* 预览区域 */}
                {previewEnabled && (
                  <div className="flex flex-col h-full">
                    <div className="flex justify-between items-center mb-2">
                      <Label className="font-semibold">实时预览</Label>
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={handleCopyPreviewContent}
                        disabled={
                          isCopying || isPreviewLoading || !processedMarkdown
                        }
                        className="flex items-center gap-2 text-xs"
                      >
                        {isCopying ? (
                          <Loader2 className="w-3 h-3 animate-spin" />
                        ) : copySuccess ? (
                          <Check className="w-3 h-3 text-green-600" />
                        ) : (
                          <Copy className="w-3 h-3" />
                        )}
                        <span className="hidden sm:inline">
                          {isCopying
                            ? "复制中..."
                            : copySuccess
                            ? "已复制"
                            : "复制预览"}
                        </span>
                      </Button>
                    </div>
                    <div className="border rounded-md flex-grow overflow-auto p-4 bg-gray-50/50 min-h-[40vh]">
                      {isPreviewLoading ? (
                        <div className="flex items-center justify-center h-full text-gray-500">
                          <Loader2 className="w-5 h-5 mr-2 animate-spin" />
                          加载预览数据中...
                        </div>
                      ) : (
                        <MarkdownPreviewRenderer content={processedMarkdown} />
                      )}
                    </div>
                  </div>
                )}
              </div>
            </TabsContent>

            {/* Word模板标签 */}
            <TabsContent value="word" className="p-4 flex-grow mt-0">
              <WordTemplateUploader
                template={currentTemplate}
                onMarkdownGenerated={handleUpdateMarkdown}
                onUploadComplete={handleUpdateTemplate}
              />
            </TabsContent>

            {/* 基本信息标签 */}
            <TabsContent value="basic_info" className="p-4 flex-grow mt-0">
              <div className="p-4 border rounded-lg bg-gray-50 h-full flex items-center justify-center text-gray-500">
                <p>基本信息表单区域（待开发）</p>
              </div>
            </TabsContent>
          </Tabs>
        </CardContent>
      </Card>

      {/* 变量参考手册 */}
      <DraggableVariableGuide
        isVisible={showVariableGuide}
        onClose={() => setShowVariableGuide(false)}
        onInsertVariable={handleInsertVariable}
      />

      {/* 全文预览模态框 */}
      {showFullPreview && (
        <div className="fixed inset-0 z-[100] bg-black bg-opacity-50 flex items-center justify-center p-4">
          <div className="bg-white rounded-lg shadow-2xl w-full h-full max-w-6xl max-h-[90vh] flex flex-col">
            <div className="flex-shrink-0 flex items-center justify-between p-4 border-b bg-gray-50">
              <div>
                <h3 className="text-lg font-semibold text-gray-900">
                  全文预览
                </h3>
                <p className="text-sm text-gray-600">
                  {selectedSchemeId
                    ? `使用方案: ${
                        schemes.find((s) => s.id === selectedSchemeId)?.name ||
                        "未知"
                      }`
                    : "未选择预览数据"}
                </p>
              </div>
              <Button
                variant="ghost"
                size="icon"
                onClick={() => setShowFullPreview(false)}
              >
                <X className="w-5 h-5" />
              </Button>
            </div>
            <div className="flex-1 overflow-y-auto p-6 bg-white">
              <div className="max-w-4xl mx-auto prose prose-lg max-w-none">
                {isPreviewLoading ? (
                  <div className="flex items-center justify-center py-12">
                    <Loader2 className="w-8 h-8 animate-spin text-blue-600 mr-3" />
                    <span>加载预览数据中...</span>
                  </div>
                ) : (
                  <MarkdownPreviewRenderer content={processedMarkdown} />
                )}
              </div>
            </div>
            <div className="flex-shrink-0 flex items-center justify-between p-4 border-t bg-gray-50">
              <div className="text-sm text-gray-600">
                {previewData ? "已应用预览数据" : "显示原始模板内容"}
              </div>
              <div className="flex gap-2">
                <Button
                  variant="outline"
                  onClick={() => setShowFullPreview(false)}
                >
                  关闭预览
                </Button>
                <Button
                  onClick={handleSave}
                  className="bg-blue-600 hover:bg-blue-700"
                >
                  <Save className="w-4 h-4 mr-2" />
                  保存模板
                </Button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default MarkdownTemplateEditor;
